package httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Sai
 * Created by Sai on 2019-03-19.
 */
@SuppressWarnings("unused")
public class QuickStart {


    public static void main(final String[] args) throws Exception {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            final HttpGet httpGet = new HttpGet("http://www.baidu.com");
            // The underlying HTTP connection is still held by the response object
            // to allow the response content to be streamed directly from the network socket.
            // In order to ensure correct deallocation of system resources
            // the user MUST call CloseableHttpResponse#close() from a finally clause.
            // Please note that if response content is not fully consumed the underlying
            // connection cannot be safely re-used and will be shut down and discarded
            // by the connection manager.
            try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
//                System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
                final HttpEntity entity1 = response1.getEntity();
                // 必须加utf-8,否则中文乱码
                System.out.println(EntityUtils.toString(entity1, "UTF-8"));
                // do something useful with the response body
                // and ensure it is fully consumed
                EntityUtils.consume(entity1);
            }

            System.out.println("我是无敌分隔线--------------------------------------------------------");

            final HttpPost httpPost = new HttpPost("http://www.baidu.com");
            final List<NameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("username", "vip"));
            nvps.add(new BasicNameValuePair("password", "secret"));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));

            try (CloseableHttpResponse response2 = httpclient.execute(httpPost)) {

//                System.out.println(response2.getCode() + " " + response2.getReasonPhrase());
                final HttpEntity entity2 = response2.getEntity();
                // 必须加utf-8,否则中文乱码
                System.out.println(EntityUtils.toString(entity2, "UTF-8"));
                // do something useful with the response body
                // and ensure it is fully consumed
                EntityUtils.consume(entity2);
            }
        }
    }

    public static String postJson(String url, Object obj) {
        Jsonb jsonb = JsonbBuilder.create();
        return postJson(url, jsonb.toJson(obj));
    }

    @SuppressWarnings("WeakerAccess")
    public static String postJson(String url, String jsonStr) {

        try {
//            JSONObject  obj = new JSONObject();
//            obj.append("app_name", "全民大讨论");
//            obj.append("app_ip", "10.21.243.234");
//            obj.append("app_port", 8080);
//            obj.append("app_type", "001");
//            obj.append("app_area", "asd");

            CloseableHttpClient httpclient = HttpClients.createDefault();
//            System.out.println(obj);

            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

            // 解决中文乱码问题
            StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8");
            stringEntity.setContentEncoding("UTF-8");

            httpPost.setEntity(stringEntity);

            // CloseableHttpResponse response =
            // httpclient.execute(httpPost);

            System.out.println("Executing request " + httpPost.getRequestLine());

            // Create a custom response handler
            ResponseHandler<String> responseHandler = response -> {
                //lambda表达式
                int status = response.getStatusLine().getStatusCode();

                if (status >= 200 && status < 300) {

                    HttpEntity entity = response.getEntity();

                    return entity != null ? EntityUtils.toString(entity) : null;

                } else {
                    throw new ClientProtocolException(
                            "Unexpected response status: " + status);
                }
            };

            String responseBody = httpclient.execute(httpPost, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);

            return responseBody;

        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String post(String url, List<NameValuePair> formparams) {
//        创建参数队列
//        List<NameValuePair> formparams = new ArrayList<>();
//        formparams.add(new BasicNameValuePair("type", "house"));

        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        UrlEncodedFormEntity uefEntity;

        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());

            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity, "UTF-8");
                    System.out.println("--------------------------------------");
                    System.out.println("Response content: " + result);
                    System.out.println("--------------------------------------");

                    return result;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
